package com.gitee.candy.configer.aspect;

import com.gitee.candy.configer.customInterface.InterfaceIpAuth;
import com.gitee.candy.other.ResultBean;
import com.gitee.candy.string.StringUtils;
import com.gitee.candy.string.UrlUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author suyanlong
 * @Version V1.0.0
 * @Date 2021/10/15 10:47
 * @Description 对外接口ip白名单权限过滤实现及监控
 */
@Aspect
@Component
public class InterfaceIpAuthAspect {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.gitee.candy.configer.customInterface.InterfaceIpAuth)")
    public void InterfaceIpAuthPointcut() {
    }

    @Around("InterfaceIpAuthPointcut()&&@annotation(interfaceIpAuth)")
    public Object InterfaceIpAuthAround(ProceedingJoinPoint pc, InterfaceIpAuth interfaceIpAuth) {
        long startTime = System.currentTimeMillis();
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String customerIP = UrlUtil.getCustomerIP(request);
            String requestURI = request.getRequestURI();

            // 解析注解中的 ip白名单
            Set<String> ipAuth = new HashSet<>();
            if (StringUtils.isNotBlank(interfaceIpAuth.value())) {
                ipAuth.add(interfaceIpAuth.value());
            }
            if (interfaceIpAuth.ips() != null && interfaceIpAuth.ips().length > 0) {
                for (int i = 0; i < interfaceIpAuth.ips().length; i++) {
                    ipAuth.add(interfaceIpAuth.ips()[i]);
                }
            }

            // 在白名单中配置的不拦截
            if (ipAuth != null && ipAuth.size() > 0 && ipAuth.contains(customerIP)) {
                Object proceed = pc.proceed();
                log.debug("处理对外接口ip白名单权限过滤时长：{}ms", (System.currentTimeMillis() - startTime));
                return proceed;
            }
            log.error("============================================");
            log.error("url=" + requestURI + "   customerIP=" + customerIP);
            log.error("============================================");
            return ResultBean.build(403, "无接口访问权限！");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            log.error("处理对外接口ip白名单权限过滤发生异常");
        }
        return null;
    }

}
